
package com.suarte.core.hibernate;
import com.suarte.core.*;
import com.suarte.core.service.PaymentStatus;
import com.suarte.core.dao.QuotationDao;
import com.suarte.core.dao.PaymentDao;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.appfuse.dao.hibernate.GenericDaoHibernate;

import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

/**
 * @date   Mar 03, 2011
 * @author Gcastillo
 */
@Repository("customerPaymentDao")
public class PaymentDaoHibernate extends GenericDaoHibernate<Payment, Long> implements PaymentDao {

    public PaymentDaoHibernate() {
        super(Payment.class);
    }

    public List<Payment> findByDescription(String description) {
        return getHibernateTemplate().find("from Payment where description like upper(?)", description.concat("%").toUpperCase());
    }

    @Transactional(readOnly = false, propagation = Propagation.REQUIRES_NEW)
    public void store(Payment object) {
        getHibernateTemplate().saveOrUpdate(object);
    }

    @Override
    public Payment get(Long id) {
        List<Payment> results = getHibernateTemplate().find("from Payment this join fetch this.paymentDetails where this.id = ?", id);
        return !results.isEmpty() ? results.get(0) : null;
    }

    public void deleteDetails(List<InvoicePayment> args) {
        getHibernateTemplate().deleteAll(args);
    }

    public List<Payment> findPayments(Long id, String description, Date date, Company company, Contact contact, PaymentStatus status) {
        String hql = "from Payment this join fetch this.company company " +
                     " where 1 = 1";
        List args = new ArrayList();

        if (id != null){
            args.add(id);
            hql += " and this.id = ?";
        }
        if (!isBlank(description)) {
            args.add(description.toUpperCase().concat("%"));
            hql += " and upper(ltrim(rtrim(this.description))) like upper(ltrim(rtrim(?)))";
        }
        if (date != null) {
            args.add(date);
            hql += " and (this.date) = (?)";
        }

        if (company != null) {
            args.add(company);
            hql += " and company = ?";
        }

        List results = getHibernateTemplate().find(hql, args.toArray());
        return results;
    }

     private boolean isBlank(String value) {
        return value == null || value.trim().length() == 0;
    }
}